package com.ad_hccm.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class TokenUtil {
    @Value("${token.privateKey}")
    private String privateKey;

    /**
     * 加密
     * @param userId 用户id
     * @param userRole 用户权限
     * @return token
     */
    public String getToken(String userId,String userRole){
        String token = JWT.create()
                .withClaim("userId",userId)
                .withClaim("userRole",userRole)
                .withClaim("timeStamp",System.currentTimeMillis())
                .sign(Algorithm.HMAC256(privateKey));
        return token;
    }

    public Map<String,String> parseToken(String token){
        HashMap<String,String> map = new HashMap<>();
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(privateKey))
                .build().verify(token);
        Claim userId = decodedJWT.getClaim("userId");
        Claim userRole = decodedJWT.getClaim("userRole");
        Claim timeStamp = decodedJWT.getClaim("timeStamp");
        map.put("userId",userId.asString());
        map.put("userRole",userRole.asString());
        map.put("timeStamp",timeStamp.asLong().toString());
        return map;
    }
}
